package com.hyk.commonLib.common.utils.dataBinding.bindingAdapter;

import android.view.View;
import android.widget.EditText;

import androidx.databinding.BindingAdapter;

import com.hyk.commonLib.common.utils.rx.EmptyObserver;
import com.jakewharton.rxbinding4.widget.RxTextView;

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.TimeUnit;

/**
 * Created by 贺玉琨 on 2021/1/13.
 */
public class EditorAdapter {
    //两次点击间的最小间隔(毫秒)
    private static final int EDITOR_ACTIONS_WINDOW_DURATION = 300;

    @BindingAdapter(value = {"editorActions", "editorActionsDebounceWindow"}, requireAll = false)
    public static void setEditorActions(EditText view, EditorActionsListener listener, Integer editorActionsDebounceWindow) {
        RxTextView.editorActions(view)
                .throttleFirst((editorActionsDebounceWindow == null || editorActionsDebounceWindow <= 0) ? EDITOR_ACTIONS_WINDOW_DURATION : editorActionsDebounceWindow, TimeUnit.MILLISECONDS)
                .subscribe(new EmptyObserver<Integer>() {
                    @Override
                    public void onNext(@NotNull Integer actionId) {
                        if (listener != null) {
                            listener.onAction(view, actionId);
                        }
                    }
                });
    }

    public interface EditorActionsListener {
        void onAction(View v, int actionId);
    }
}
